/*
 *  textscreen.c
 *  xD-OS
 *
 *  Created by James Johns on 22/07/2009.
 *  Copyright 2009 xD-Dunce. All rights reserved.
 *
 */

#include "global.h"
#include "textscreen.h"
#include "stdio.h"




void initScreen(){
	screen = (Byte *)0xb8000;
	attributes = ((BLACK << 4) | (WHITE & 0x0F));
	clearScreen();
	updateCursor();
}


void clearScreen(){
	int i;
	for(i = 0; i<(80*2*25); i += 2){
		screen[i] = 0x20;
		screen[i+1] = attributes;
	}
	cursorX = cursorY = 0;
}


void updateCursor(){
	Word pos = cursorY *80 +cursorX;
	
	outB(0x3D4, 14);
	outB(0x3D5, pos>>8);
	outB(0x3D4, 15);
	outB(0x3D5, pos);
}

void printChar(Byte c){
	if(c == '\n'){
		newLine();
	}
	else{
		Word pos = (cursorY *80 +cursorX)*2;
		screen[pos] = c;
		screen[pos+1] = attributes;
		cursorX++;
	}
	if(cursorX > 80){
		cursorX = 0;
		cursorY++;
	}
	if(cursorY > 24){
		scroll();
	}
}

void printString(Byte *string){
	int i;
	dWord length = strlen(string);
	for(i = 0; i<length; i++){
		printChar(string[i]);
	}
	updateCursor();
}

void printHex(dWord h){
	printString("0x");
	Byte val;
	signed int count = 7;
	while(count >= 0){
		val = (h >> count*4)&0x0F;
		switch(val){
			case 0:
				printChar('0');
				break;
			case 1:
				printChar('1');
				break;
			case 2:
				printChar('2');
				break;
			case 3:
				printChar('3');
				break;
			case 4:
				printChar('4');
				break;
			case 5:
				printChar('5');
				break;
			case 6:
				printChar('6');
				break;
			case 7:
				printChar('7');
				break;
			case 8:
				printChar('8');
				break;
			case 9:
				printChar('9');
				break;
			case 10:
				printChar('A');
				break;
			case 11:
				printChar('B');
				break;
			case 12:
				printChar('C');
				break;
			case 13:
				printChar('D');
				break;
			case 14:
				printChar('E');
				break;
			case 15:
				printChar('F');
				break;
		}
		count--;
	}
}

void newLine(){
	cursorX = 0;
	cursorY++;
	if(cursorY > 24){
		scroll();
	}
}

void scroll(){
	int i;
	for(i = 0; i < 24*80*2; i++){
		screen[i] = screen[i+160];
	}
	for(i = 24*80*2; i < 25*80*2; i++){
		screen[i++] = 0x20;
		screen[i] = attributes;
	}
	cursorY = 24;
	cursorX = 0;
}



